package org.Util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.cladwell.exception.ConditionException;

import java.util.Calendar;
import java.util.Date;

public class TkoenUtil {
    private static final String issure="clad";
    public  static  String generateToken(Long userid) throws Exception {
        Algorithm algorithm=Algorithm.RSA256(RSAUtil.getPublicKey(),RSAUtil.getPrivateKey());
//        为什么要用RSA因为我们已经有了RSA
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.SECOND,30);
        return JWT.create().withKeyId(String.valueOf(userid))
                .withIssuer(issure)
                .withExpiresAt(calendar.getTime())
                .sign(algorithm);
    }
    public  static Long verifyToken(String token)  {

        Algorithm algorithm = null;
        try {
            algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey());
            JWTVerifier jwtVerifier=JWT.require(algorithm).build();
            DecodedJWT verify = jwtVerifier.verify(token);
            String keyId = verify.getKeyId();
            return Long.valueOf(keyId);
        } catch (TokenExpiredException e) {
            throw new ConditionException("555","Token过期");
        }catch (Exception e){
            throw new ConditionException("500","非法用户Token");
        }


    }
}
